#!/bin/bash
repo_path=""
rpm_name=""
tmp_path=/opt/tmp_rpms_source
ali_key=("linux.alibaba.com" "antfin.com" "taobao.com")
huawei_key=("huawei.com" "hisilicon.com")
current_path=$(
    cd "$(dirname $0)"
    pwd
)
result_file=${tmp_path}/result.log
repo_branch="master"
skip=""

function pre_env() {
    if [ ! -d ${tmp_path} ]; then
        mkdir -p ${tmp_path}
        echo "[INFO] Create tmp path ${tmp_path}"
    fi
    cd ${tmp_path}
    rm -rf ${rpm_name}
}

function git_clone() {
    echo "[INFO] Start to git clone ${rpm_name}"
    git_status=$(rpm -qa git)
    if [[ -z ${git_status} ]]; then
        yum install git -y
        git_status=$(rpm -qa git)
        if [[ -z ${git_status} ]]; then
            echo "[ERROR] Git install failed"
            exit 1
        fi
    fi

    cd ${tmp_path}

    git clone -b ${repo_branch} https://gitee.com/${repo_path}/${rpm_name}.git >/dev/null
    rpm_path=$(ls | grep ${rpm_name})
    if [[ -z ${rpm_path} ]]; then
        echo "[ERROR] No package ${rpm_name} is found, please check path /opt/cve_patch_tmp"
        skip="yes"
    fi
}

function search_key() {
    echo "[INFO] Start to search key in git_log"
    cd ${tmp_path}/${rpm_name}
    git log --oneline --author=linux.alibaba.com --author=antfin.com --author=taobao.com >${rpm_name}_ali.log
    ali_key_num=$(cat ${rpm_name}_ali.log | wc -l)
    echo "[INFO] ${rpm_name} has ali key num is ${ali_key_num}"
    echo "[INFO] ${rpm_name} has ali key num is ${ali_key_num}" >>${result_file}

    git log --oneline --author=huawei.com --author=hisilicon.com --author='Mauro Carvalho Chehab' >${rpm_name}_hw.log
    hw_key_num=$(cat ${rpm_name}_hw.log | wc -l)
    echo "[INFO] ${rpm_name} has huawei key num is ${hw_key_num}"
    echo "[INFO] ${rpm_name} has huawei key num is ${hw_key_num}" >>${result_file}
    echo "++++++++++++++++++++++++++++++++++++++++++++"
    echo "++++++++++++++++++++++++++++++++++++++++++++" >>${result_file}
}

function start() {
    if [[ -f ${result_file} ]];then
        echo "" >${result_file}
    fi
    rpms=$(cat ${current_path}/rpms.txt)
    for rpm in ${rpms[@]}; do
        if [[ -n ${rpm} ]]; then
            repo_path=$(echo ${rpm} | awk -F '/' '{print $1}')
            rpm_name=$(echo ${rpm} | awk -F '/' '{print $2}')
            branch_name=$(echo ${rpm} | awk -F '/' '{print $3}')
            if [[ -n ${branch_name} ]];then
                repo_branch=${branch_name}
            fi
            pre_env
            git_clone
            if [[ -z ${skip} ]]; then
                search_key
            fi
        fi
    done
}

start
